#!/usr/bin/env python
#  -*- coding: utf-8 -*-
import os
import sqlite3
import sys
import time
import keyboard
import requests
from zhuui import Ui_MainWindow
from shezhiui import Ui_MainWindow2
from zuozijiance import ZuozitaoshiWindow
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QMainWindow, QApplication, QSystemTrayIcon, QMenu, QAction, QLineEdit, QMessageBox
from PyQt5.QtCore import pyqtSignal, Qt, QThread, QEvent  # Qt的曹信号对象，多线程对象等


class MainWindow(QMainWindow, Ui_MainWindow):
    """主窗口"""
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)
        self.setWindowIcon(QIcon("666.ico"))  # 设置窗口图标
        self.lineEdit.setEchoMode(QLineEdit.Password)  # 设置为密码输入框
        # 禁用最小化按钮
        # self.setWindowFlags(self.windowFlags() & ~Qt.WindowMinimizeButtonHint)
        # 禁用关闭按钮
        # self.setWindowFlags(self.windowFlags() & ~Qt.WindowCloseButtonHint)
        self.label_4.setAlignment(Qt.AlignCenter)  # 设置字体居中显示
        # 将按钮的 clicked 信号连接到自定义的槽函数
        self.pushButton.clicked.connect(self.on_button_shezhi)  # 设置
        self.pushButton_2.clicked.connect(self.on_button2_gbrj)  # 关闭软件
        self.pushButton_3.clicked.connect(self.on_button3_czsj)  # 重置使用时间
        self._initTrayIcon()
        self._shezhi = SettingsWindow()
        self._shezhi.chuanshezhi.connect(self.shezhi_chuanru)
        self._shezhi.zuozijiance.zuozixinxi.connect(self.zuozibudui_chuli)  # 坐姿不对处理

        self._qudongqi = QudongQi()
        self.shezhi_chuanru(self._shezhi.shezhi)
        self._qudongqi.shijianxianshi.connect(self.shijian_xianshi)  # 连接实时显示时间
        self._qudongqi.suoding.connect(self.suoding)  # 锁定屏幕
        self._qudongqi.shengyushijian.connect(self.shengyushijian_xianshi)  # 剩余时间显示
        self._qudongqi.start()  # 启动驱动
        self._zhenguanbiruanjian = False
        self.hide()  # 隐藏到工具栏

    def _initTrayIcon(self):
        # 创建系统托盘图标
        self.tray_icon = QSystemTrayIcon(self)
        self.tray_icon.setIcon(QIcon("666.ico"))  # 设置托盘图标，需要一个图标文件
        self.tray_icon.setVisible(True)
        # 创建托盘图标菜单
        menu = QMenu(self)
        show_action = QAction("显示窗口", self)
        show_action.triggered.connect(self.showWindow)
        menu.addAction(show_action)
        self.tray_icon.setContextMenu(menu)
        # 设置双击托盘图标显示窗口
        self.tray_icon.activated.connect(self.onTrayIconActivated)

    def closeEvent(self, event):
        """关闭软件事件重写"""
        self._shezhi.close()  # 先关闭设置
        self._shezhi.zuozijiance.close()
        if self._zhenguanbiruanjian:
            self.close()
        else:
            # 窗口关闭时隐藏到托盘
            event.ignore()  # 忽略最关闭事件
            self.hide()  # 隐藏到系统托盘

    def changeEvent(self, event):
        """最小化事件重写"""
        # 捕获窗口状态变化事件
        if event.type() == QEvent.WindowStateChange:
            if self.windowState() & Qt.WindowMinimized:
                event.ignore()  # 忽略最小化事件
                self.hide()  # 隐藏到系统托盘

    def showWindow(self):
        # 显示窗口并激活
        self.showNormal()
        self.activateWindow()

    def onTrayIconActivated(self, reason):
        # 双击托盘图标时显示窗口
        if reason == QSystemTrayIcon.ActivationReason.Trigger:
            self.showWindow()

    def shezhi_chuanru(self, shezhi):
        """将设置传递给驱动程序"""
        print(shezhi)
        self._qudongqi.shezhi = shezhi
        self.label_4.setText(str(shezhi['allowed_duration']))
        self.showNormal()  # 恢复窗口大小

    def _block_keys(self):
        """禁用win功能键和任务管理器功能"""
        # 按键映射
        keys_to_block = [
            "windows",  # Windows 键
            "ctrl",  # Ctrl 键
            "alt",
            "delete",
            "left windows",  # 左 Windows 键
            "right windows",  # 右 Windows 键
            "right alt",
            "right alt",
            "left ctrl",  # 左 Ctrl 键
            "right ctrl",  # 右 Ctrl 键
            "right alt",
            "right alt"
        ]
        # 阻止按键的默认行为
        for key in keys_to_block:
            keyboard.block_key(key)
        print("Windows 键和 Ctrl 键已被禁用。")

    def _unblock_keys(self):
        """解除按键禁止功能"""
        keyboard.unhook_all()
        print("Windows 键和 Ctrl 键已恢复正常使用。")

    def on_button_shezhi(self, agr):
        """调用设置"""
        if self._shezhi.shezhi['password'] == self.lineEdit.text():
            self.lineEdit.setText("")  # 清空密码
            self._shezhi.chushihua_uisj()
            self._shezhi.show()
        else:
            QMessageBox.warning(self, '登录失败', '密码错误，请重试！', QMessageBox.Ok)

    def on_button2_gbrj(self, agr):
        """关闭软件"""
        if self._shezhi.shezhi['password'] == self.lineEdit.text():
            self._zhenguanbiruanjian = True
            self.close()
        else:
            QMessageBox.warning(self, '登录失败', '密码错误，请重试！', QMessageBox.Ok)

    def on_button3_czsj(self, agr):
        """重置时间"""
        if self._shezhi.shezhi['password'] == self.lineEdit.text():
            self.lineEdit.setText("")  # 清空密码
            conn = sqlite3.connect('settings.db3')
            cursor = conn.cursor()
            cursor.execute(f"UPDATE settings SET used_time = {self._shezhi.shezhi['allowed_duration']} WHERE id = 1")
            conn.commit()
            conn.close()
            self.label_4.setText(str(self._shezhi.shezhi['allowed_duration']))
            self.showNormal()  # 恢复窗口大小
            self._unblock_keys()  # 恢复键盘使用
        else:
            QMessageBox.warning(self, '重置失败', '密码错误，请重试！', QMessageBox.Ok)

    def shijian_xianshi(self, nr):
        """刷新时间显示"""
        self.label_2.setText(nr)

    def shengyushijian_xianshi(self, nr):
        """剩余时间显示"""
        self.label_4.setText(nr)

    def suoding(self):
        """锁定屏幕"""
        self.showFullScreen()  # 置顶，遮住全屏。
        self._block_keys()
        os.system("rundll32.exe user32.dll,LockWorkStation")  # 锁定电脑屏幕

    def zuozibudui_chuli(self, nr, zt):
        """坐姿不正常处理"""
        if zt:
            # self.showFullScreen()  # 置顶，遮住全屏。
            self._shezhi.zuozijiance.showFullScreen()  # 置顶，遮住全屏。
        else:
            self._shezhi.zuozijiance.showNormal()  # 恢复窗口大小

        self.label_7.setText(nr)


class QudongQi(QThread):
    """驱动器"""
    shijianxianshi = pyqtSignal(str)
    shengyushijian = pyqtSignal(str)
    suoding = pyqtSignal()

    def __init__(self):
        super().__init__()
        self.shezhi = None
        self._dangqianshijian = None
        self._dangqianriqi = None
        self._lstime = time.time()

    def _get_beijing_time(self):
        # 接口地址
        url = "https://cn.apihz.cn/api/time/getapi.php"
        # 请求参数（使用公共ID和KEY，建议替换为自己的ID和KEY）
        params = {
            "id": "88888888",
            "key": "88888888",
            "type": 2  # 返回标准时间格式（精确到秒）
        }
        nr = ""
        try:
            # 发送GET请求
            response = requests.get(url, params=params)
            # 检查请求是否成功
            if response.status_code == 200:
                data = response.json()  # 解析返回的JSON数据
                if data["code"] == 200:
                    # 获取返回的时间
                    beijing_time = data["msg"]
                    # print(beijing_time)
                    nr = beijing_time
                else:
                    print("时间接口返回错误")
            else:
                print("请求失败，状态码")
        except Exception:
            print("请求过程中发生错误")

        return nr

    def _fasong_jishi(self):
        """发送时间显示"""
        riqishijian = self._get_beijing_time()

        if riqishijian:
            self._dangqianshijian = int(riqishijian[-8:].replace(":", ""))/10000
            self._dangqianriqi = int(riqishijian[:-9].replace("-", ""))
            # print(self._dangqianriqi)
            self.shijianxianshi.emit(riqishijian)

    def run(self):
        """循环检测"""
        conn = sqlite3.connect('settings.db3')
        cursor = conn.cursor()
        cursor.execute('SELECT used_time,date FROM settings WHERE id = 1')
        sysj = cursor.fetchone()
        # 下一天重置可用时间时间
        if sysj[1] != self._dangqianriqi:
            cursor.execute('''
                UPDATE settings
                SET 
                    used_time = ?,
                    date = ? 
                WHERE id = 1
            ''', (self.shezhi['allowed_duration'], self._dangqianriqi))
            self.shengyushijian.emit(str(self.shezhi['allowed_duration']))
        else:
            self.shengyushijian.emit(str(sysj[0]))

        while 1:
            try:
                self._fasong_jishi()
                # print(self.shezhi['start_time'], self._dangqianshijian, self.shezhi['end_time'])
                shijian = int(time.time())
                if shijian % 60 == 0 or shijian-self._lstime > 62:
                    self._lstime = shijian
                    cursor.execute('SELECT used_time,date FROM settings WHERE id = 1')
                    sysj = cursor.fetchone()
                    # 下一天重置可用时间时间
                    if sysj[1] != self._dangqianriqi:
                        cursor.execute('''
                            UPDATE settings
                            SET 
                                used_time = ?,
                                date = ? 
                            WHERE id = 1
                        ''', (self.shezhi['allowed_duration'], self._dangqianriqi))
                        self.shengyushijian.emit(str(self.shezhi['allowed_duration']))
                        continue

                    # 计算剩余时间
                    if self.shezhi['start_time'] < self._dangqianshijian < self.shezhi['end_time'] and sysj[0] > 0:
                        shegnyushijian = sysj[0]-1
                        self.shengyushijian.emit(str(shegnyushijian))
                        cursor.execute('''
                            UPDATE settings
                            SET 
                                used_time = ? 
                            WHERE id = 1
                        ''', (shegnyushijian,))

                        conn.commit()
                    else:
                        self.suoding.emit()
            except:
                print("循环检测错误")

            self.sleep(1)


class SettingsWindow(QMainWindow, Ui_MainWindow2):
    chuanshezhi = pyqtSignal(dict)
    """设置窗口"""
    def __init__(self):
        super(SettingsWindow, self).__init__()
        self.setupUi(self)
        self.shezhi = None
        self._create_database()  # 创建库数据表
        self._load_settings()
        self.chushihua_uisj()

        self.pushButton.clicked.connect(self.on_button_baocunshezhi)  # 保存设置
        self.pushButton_2.clicked.connect(self.on_button2_zuozitiaoshi)  # 坐姿检测调试
        self.lineEdit_4.setEchoMode(QLineEdit.Password)  # 隐藏为密码
        # 连接复选框的状态变化信号到槽函数
        self.checkBox_2.stateChanged.connect(self.toggle_password_visibility)
        self.zuozijiance = ZuozitaoshiWindow()  # 坐姿检测调试

    def chushihua_uisj(self):
        """初始化设置界面数据"""
        self.lineEdit.setText("{:.2f}".format(self.shezhi['start_time']))
        self.lineEdit_2.setText("{:.2f}".format(self.shezhi['end_time']))
        self.lineEdit_3.setText(str(self.shezhi['allowed_duration']))
        self.lineEdit_4.setText(self.shezhi['password'])
        self.checkBox.setChecked(self.shezhi['is_sitting_detection'])

    def _create_database(self):
        """创建数据库和表（如果表不存在）"""
        conn = sqlite3.connect('settings.db3')
        cursor = conn.cursor()

        # 检查 settings 表是否存在
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='settings'")
        table_exists = cursor.fetchone() is not None

        if not table_exists:
            # 创建 settings 表（如果表不存在）
            cursor.execute('''
                CREATE TABLE settings (
                    id INTEGER PRIMARY KEY,
                    start_time DOUBLE,
                    end_time DOUBLE,
                    allowed_duration INTEGER,
                    password TEXT,
                    used_time INTEGER,
                    is_sitting_detection BOOLEAN,
                    date INTEGER
                )
            ''')
            conn.commit()
            print("设置表不存在，已经创建。")

            # 初始化数据
            cursor.execute('''
                INSERT OR REPLACE INTO settings (id, start_time, end_time, allowed_duration, password, used_time, 
                is_sitting_detection, date) VALUES (1, ?, ?, ?, ?, ?, ?, ?)
            ''', (8.28, 22.18, 120, '123456', 120, True, 20250305))
            conn.commit()
            # 初始化设置表
            self.shezhi = {
                'start_time': 8.28,
                'end_time': 22.18,
                'allowed_duration': 120,
                'password': '123456',
                'used_time': 120,
                'is_sitting_detection': True,
                'date': 20250305
            }


        conn.close()
        return table_exists

    def _load_settings(self):
        """读取数据库配置文件"""
        conn = sqlite3.connect('settings.db3')
        cursor = conn.cursor()

        cursor.execute('SELECT * FROM settings WHERE id = 1')
        row = cursor.fetchone()

        if row:
            id, start_time, end_time, allowed_duration, password, used_time, is_sitting_detection, date = row
            self.shezhi = {
                'start_time': start_time,
                'end_time': end_time,
                'allowed_duration': allowed_duration,
                'password': password,
                'used_time': used_time,
                'is_sitting_detection': bool(is_sitting_detection),
                'date': date
            }

            self.chuanshezhi.emit(self.shezhi)

    def on_button_baocunshezhi(self):
        """保存设置"""
        start_time = float(self.lineEdit.text())
        end_time = float(self.lineEdit_2.text())
        allowed_duration = int(self.lineEdit_3.text())
        password = self.lineEdit_4.text()
        is_sitting_detection = self.checkBox.isChecked()
        self.shezhi['start_time'] = start_time
        self.shezhi['end_time'] = end_time
        self.shezhi['allowed_duration'] = allowed_duration
        self.shezhi['password'] = password
        self.shezhi['used_time'] = allowed_duration
        self.shezhi['is_sitting_detection'] = is_sitting_detection
        self.chuanshezhi.emit(self.shezhi)  # 跟新驱动设置
        # 更新设置
        conn = sqlite3.connect('settings.db3')
        cursor = conn.cursor()
        cursor.execute('''
            UPDATE settings
            SET 
                start_time = ?,
                end_time = ?,
                allowed_duration = ?,
                password = ?,
                used_time = ?,
                is_sitting_detection = ?
            WHERE id = 1
        ''', (start_time, end_time, allowed_duration, password, allowed_duration, is_sitting_detection))

        conn.commit()
        conn.close()

    def on_button2_zuozitiaoshi(self):
        """坐姿检测调试"""
        self.zuozijiance.show()

    def toggle_password_visibility(self, state):
        """
        根据复选框的状态切换lineEdit_4的echoMode。

        :param state: Qt.CheckState 枚举值，表示复选框的状态
        """
        if state == 2:  # Qt.Checked
            self.lineEdit_4.setEchoMode(QLineEdit.Normal)  # 显示明文
        else:
            self.lineEdit_4.setEchoMode(QLineEdit.Password)  # 隐藏为密码


if __name__ == '__main__':
    app_anquantuichu = QApplication(sys.argv)  # 退出时确保完全退出
    mainWindow = MainWindow()
    mainWindow.show()  # 启动主窗口
    # mainWindow.showMinimized()  # 程序启动时最小化
    sys.exit(app_anquantuichu.exec_())  # 程序运行，方法确保程序完整退出
